package cn.wolfcode.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class OSSUtils {
    @Value("${aliyun.oss.endpoint}")
   private String endpoint ;
    @Value("${aliyun.oss.accessKeyId}")
   private String accessKeyId ;
    @Value("${aliyun.oss.accessKeySecret}")
   private String accessKeySecret ;
    @Value("${aliyun.oss.bucketName}")
   private String bucketName;

    public String upload(MultipartFile file) throws IOException {

        //获取上传文件的输入流
        InputStream inputStream = file.getInputStream();
        //避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String exName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + exName;
        //构建客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //上传文件
        ossClient.putObject(bucketName, newFileName, inputStream);
        //关闭客户端
        ossClient.shutdown();
        //拼接返回的URL 指定位置插入指定的字符序列
        StringBuffer sb = new StringBuffer(endpoint);
        StringBuffer urlsb = sb.insert(8, bucketName + ".").append("/").append(newFileName);

        return urlsb.toString();

    }

}
